<template lang="">
  <div>
    <div>样条曲线</div>
    <div ref="webgl" id="webgl" style="width: 800px; height: 500px"></div>
  </div>
</template>
<script setup lang="ts">
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  let scene: any = null;
  let camera: any = null;
  let render: any = null;
  onMounted(() => {
    init();
  });

  function init() {
    scene = new THREE.Scene();
    const width = 500;
    const height = 300;
    camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(-100, 300, 300);
    camera.lookAt(scene.position);
    render = new THREE.WebGLRenderer();
    render.setSize(width, height);
    // console.log(' webgl.value', webgl.value);

    webgl.value.appendChild(render.domElement);
    // document.body.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);
    // 三维向量Vector3创建一组顶点坐标
    // const arr = [
    //   new THREE.Vector3(-50, 20, 90),
    //   new THREE.Vector3(-10, 40, 40),
    //   new THREE.Vector3(0, 0, 0),
    //   new THREE.Vector3(60, -60, 0),
    //   new THREE.Vector3(70, 0, 80),
    // ];
    // // 三维样条曲线
    // const curve = new THREE.CatmullRomCurve3(arr);

    // 二维向量Vector2创建一组顶点坐标
    const arr = [new THREE.Vector2(-100, 0), new THREE.Vector2(0, 30), new THREE.Vector2(100, 0)];
    // 二维样条曲线
    const curve = new THREE.SplineCurve(arr);
    //曲线上获取点
    const pointsArr = curve.getPoints(50);
    const geometry = new THREE.BufferGeometry().setFromPoints(pointsArr);

    // 线材质
    const material = new THREE.LineBasicMaterial({
      color: 0x00fffff,
    });
    // 线模型
    const line = new THREE.Line(geometry, material);
    scene.add(line);

    // 用点模型可视化样条曲线经过的顶点位置
    const geometry2 = new THREE.BufferGeometry().setFromPoints(arr);
    const material2 = new THREE.PointsMaterial({
      color: 0xff00ff,
      size: 10,
    });
    //点模型对象
    const points = new THREE.Points(geometry2, material2);
    points.translateZ(2);
    scene.add(points);

    renderFun();
  }
  function renderFun() {
    render.render(scene, camera);
    requestAnimationFrame(renderFun);
  }
</script>
<style lang=""></style>
